package com.zxbg.controller.systemtoolsController;

import com.zxbg.controller.Code;
import com.zxbg.controller.Result;
import com.zxbg.domain.Role;
import com.zxbg.service.systemtoolsService.RoleManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/RoleManagement")
public class RoleManagementController {
    @Autowired
    RoleManagementService roleManagementService;

    @PostMapping
    public Result getAllRole(@RequestBody Map<String, Object> search_info, @RequestHeader Integer tenant_id) {
        List<Role> roleList = roleManagementService.getAllRole(search_info, tenant_id);
            List<Role> resList = new ArrayList<>();
        Integer startNum = ((Integer)search_info.get("current_page") - 1) * (Integer)search_info.get("page_size");
        Integer endNum = (Integer)search_info.get("current_page") * (Integer)search_info.get("page_size") - 1;
        for (int i = 0; i < roleList.size(); i++) {
            if(i >= startNum && i <= endNum) {
                resList.add(roleList.get(i));
            }
        }
        Map<String,Object> first_map = new HashMap<>();
        Map<String,Object> second_map = new HashMap<>();
        second_map.put("page_size", search_info.get("page_size"));
        second_map.put("current_page", search_info.get("current_page"));
        second_map.put("total", roleList.size());
        first_map.put("page", second_map);
        first_map.put("rows", resList);
        return new Result(Code.GET_OK, first_map);
    }

    @PostMapping("/addRole")
    public Result addRole(@RequestBody Role role, @RequestHeader Integer tenant_id) {
        role.setTenant_id(tenant_id);
        String info = roleManagementService.addRole(role);
        return new Result(info.equals("") ? Code.SAVE_OK : Code.SAVE_ERR, info, info);
    }

    @PutMapping
    public Result editRole(@RequestBody Role role) {
        boolean flag = roleManagementService.editRole(role);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    }

    @PutMapping("/{code}")
    public Result stopRole(@PathVariable String code, @RequestHeader Integer tenant_id) {
        return new Result(Code.UPDATE_OK, roleManagementService.stopRole(code, tenant_id));
    }

    @PutMapping("/runRole/{code}")
    public Result runRole(@PathVariable String code, @RequestHeader Integer tenant_id) {
        return new Result(Code.UPDATE_OK, roleManagementService.runRole(code, tenant_id));
    }

    @DeleteMapping("/{code}")
    public Result deleteRole(@PathVariable String code, @RequestHeader Integer tenant_id) {
        return new Result(Code.DELETE_OK, roleManagementService.deleteRole(code, tenant_id));
    }
}
